package controller;

import helper.Formatter;
import helper.UserSession;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import model.*; 

import org.mybeans.dao.DAOException;

import databeans.Customer;
import databeans.Employee;
import databeans.Fund;
import databeans.FundHistory;
import databeans.Transaction;

/*
 * @Xiao Liang
 * Customer Use Case: View Transaction History
 */
public class EmployeeViewCustomerTransactionHistoryAction extends Action{

	private TransactionDAO transactionDAO; 
	private FundHistoryDAOSQL fundHistoryDAOSQL; 
	private FundDAO fundDAO; 

	public EmployeeViewCustomerTransactionHistoryAction(Model model) {
		model.getPositoinDAO(); 
		fundHistoryDAOSQL = model.getFundHistoryDAOSQL(); 
		transactionDAO = model.getTransactionDAO(); 
		fundDAO        = model.getFundDAO(); 
	}

	public String getName() { return "employeeViewTransactionHistory.do"; }

	public String perform(HttpServletRequest request) {
        // define target page
		String loginPageAjax   = "common/messages.jsp";
		String loginPage = "employee/employee-login.jsp";
        String successPage = "employee/trans-history.jsp"; 
        String originPage  = successPage;
        
        // Set up the errors list
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        String type = (String)request.getParameter("type");
        System.out.println("================= >>> type = " + type);
        
        Employee employee = null;
        Customer customer = null;
        
        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = UserSession.getLoggedInEmployee(request);
        
        if (employee == null) {
        	if(type!=null && type.equals("ajax"))
        	{
        		errors.add("Your session has timed out. Please Login again. <a href=\"employeeHome.do\">Login</a> ");
        		return loginPageAjax;
        	}else
        	{
        		errors.add("You need to log in");
                return loginPage ;
        	}
        }
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer != null) {
            request = UserSession.removeCustomerFromSession(request);
            errors.add("This section is closed for customer");
            return loginPage;
        }
        
		try {

	        
			//get customer id
	        String txtCustomerID = request.getParameter("customerID");
	        System.out.println("Got Customer ID = " + txtCustomerID);
	        if((txtCustomerID==null)||(txtCustomerID.trim().equals("")))return originPage; 
	        
  			int customerID = Integer.parseInt(txtCustomerID);  
  			Transaction[] transactions = transactionDAO.getTransactions(customerID);
  			System.out.println("Transactions got = " + transactions.length);
  			
  			request.setAttribute("customerID", txtCustomerID);
  			//request.setAttribute("transactions", transactions);
  			
  			List<Integer> transIDs = new ArrayList<Integer>();
  			List<String> transDates_submit = new ArrayList<String>();
  			List<String> transDates_execute = new ArrayList<String>();
  			List<String> transTypes = new ArrayList<String>(); 
  			List<String> fundNames = new ArrayList<String>(); 
  			List<Long> numOfShares = new ArrayList<Long>(); 
  			List<Long> sharePrices = new ArrayList<Long>();
  			List<Long> amounts = new ArrayList<Long>(); 
  			List<String> statuses = new ArrayList<String>(); 
  			SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy");
  			
  			for(int i=0; i<transactions.length; i++){
  				//display fundName
  				int fundID = transactions[i].getFundID();
  				if (fundID != -1) {
  					System.out.println("Getting Fund Name");
	  				Fund fund = fundDAO.lookup(fundID);
	  				fundNames.add(fund.getName());
	  				transIDs.add(transactions[i].getTransactionID());
	  				
	  				//display transactionDate
	  				System.out.println("execute date = " + transactions[i].getExecuteDate());
	  				System.out.println("submission date = " + transactions[i].getSubmissionDate());
	  				System.out.println("formatted submission date = " + format.format(transactions[i].getSubmissionDate()));
	  				
	  				if(transactions[i].getExecuteDate()==null){
	  					System.out.println("Execute date is null");
	  					transDates_submit.add(format.format(transactions[i].getSubmissionDate()));
	  					transDates_execute.add(" - ");
	  					numOfShares.add(Long.parseLong("0"));
	  				}else{
	  					transDates_submit.add(format.format(transactions[i].getSubmissionDate()));
	  					transDates_execute.add(format.format(transactions[i].getExecuteDate()));
	  				}
	  				numOfShares.add(transactions[i].getShares());
	  				//System.out.println("trans date = " + format.format(transactions[i].getExecuteDate()));
	  				//transDates.add(format.format(transactions[i].getExecuteDate()));
	  				
	  				//display transactionType
	  				transTypes.add(Formatter.transactionType(transactions[i].getTransactionType()));
	  				
	  				//display sharePrice
	  				if(transactions[i].getExecuteDate()==null) sharePrices.add(Long.parseLong("-1")); 
	  				else {
	  					Date executeDate = transactions[i].getExecuteDate();
		 				Calendar cal = Calendar.getInstance();
		 				cal.setTime(executeDate); 
	  					 FundHistory fundHistory = fundHistoryDAOSQL.lookup(fundID, cal);
	  				     if(fundHistory==null) sharePrices.add(Long.parseLong("0")); 
	  				     else sharePrices.add(fundHistory.getPrice());
	  				}
	  				
	  				//display amount
	  				amounts.add(transactions[i].getAmount());
	  				
	  				System.out.println("Set Status");
	  				//display status: Pending or Not Pending
	 				if (transactions[i].getExecuteDate()==null) 
 						statuses.add("Pending"); 
	  				else 
	  					statuses.add("Approved");
  				}
  			}
  			
  			request.setAttribute("transIDs", transIDs);
  			request.setAttribute("transDates_submit", transDates_submit);
  			request.setAttribute("transDates_execute", transDates_execute);
  			request.setAttribute("transTypes", transTypes);
  			request.setAttribute("fundNames", fundNames);
  			request.setAttribute("numOfShares", numOfShares);
  			request.setAttribute("sharePrices", sharePrices);
  			request.setAttribute("amounts", amounts);
  			request.setAttribute("statuses", statuses); 

	        return successPage;
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return successPage;
        }
    }
	
}
